﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microhard.FMCG.Buz.Interfaces;
using Microhard.Core.Net;
using System.Net;
using System.IO;
using System.Collections.Specialized;
using Microhard.FMCG.Buz.Models;
using System.Web;
using Microhard.Core.Extensions;
using Microhard.Core;

namespace Microhard.FMCG.Buz.Impls.KASystem.WUMart
{
    public class WUMartImpl : IKASystem
    {
        private CookieContainer cookie = new CookieContainer();
        private static DateTime LastQueryStatementTime;

        public LoginResultModel Login(string userName, string pwd, string validCode)
        {
            LoginResultModel rtn = new LoginResultModel();

            //获得登录页面
            string loginUrl = "http://bjvrm.wumart.com/Index.aspx";
            string html = null;
            try
            {
                string srcString = HttpReader.HttpGet(loginUrl);

                //获得 ViewState                
                string viewStateFlag = "id=\"__VIEWSTATE\" value=\"";
                int i = srcString.IndexOf(viewStateFlag) + viewStateFlag.Length;
                int j = srcString.IndexOf("\"", i);
                string viewState = srcString.Substring(i, j - i);

                //获得 EventValidation                
                string eventValidationFlag = "id=\"__EVENTVALIDATION\" value=\"";
                i = srcString.IndexOf(eventValidationFlag) + eventValidationFlag.Length;
                j = srcString.IndexOf("\"", i);
                string eventValidation = srcString.Substring(i, j - i);

                // Convert the text into the url encoding string
                viewState = System.Web.HttpUtility.UrlEncode(viewState);
                eventValidation = System.Web.HttpUtility.UrlEncode(eventValidation);

                // Concat the string data which will be submit
                StringBuilder nvc = new StringBuilder();
                nvc.Append("__VIEWSTATE=" + viewState);
                nvc.Append("&__EVENTVALIDATION=" + eventValidation);
                nvc.Append("&Login_Div%24userCode=" + userName);
                nvc.Append("&Login_Div%24password=" + pwd);
                nvc.Append("&Login_Div%24CheckCode=" + validCode);
                nvc.Append("&Login_Div%24LoginBtn.x=40");
                nvc.Append("&Login_Div%24LoginBtn.y=4");

                html = HttpReader.HttpPostWith302(loginUrl, nvc.ToString(), "http://bjvrm.wumart.com/", ref cookie);
            }
            catch (Exception ex)
            {
                Log.Error("Login", ex);
            }
            if (!string.IsNullOrEmpty(html))
            {
                IHtmlParser<LoginResultModel> loginParser = new LoginParser();
                rtn = loginParser.ParseObject(html);
            }
            return rtn;
        }

        public List<OrderModel> GetOrder(DateTime from, DateTime to, out bool isError)
        {
            isError = false;
            List<OrderModel> result = new List<OrderModel>();
            //请求订单页面
            string orderUrl = "http://bjvrm.wumart.com/PurchaseOrder/SupPOsPrint.aspx";
            string orderHtml = null;
            try
            {
                string srcString = HttpReader.HttpGet(orderUrl, ref cookie);

                //分析Get到的数据是否有302跳转到Timeout.aspx或者Error.aspx
                IHtmlParser<HtmlModel> getParser = new Page302ToErrorOrTimePageParser();
                var getResult = getParser.ParseObject(srcString);
                //Get出现错误，则返回
                if (getResult.IsError)
                {
                    isError = getResult.IsError;
                    Log.Error("GetOrder", "Url:" + orderUrl + "&Error" + getResult.Html);
                    return result;
                }

                //获得 ViewState                
                string viewStateFlag = "id=\"__VIEWSTATE\" value=\"";
                int i = srcString.IndexOf(viewStateFlag) + viewStateFlag.Length;
                int j = srcString.IndexOf("\"", i);
                string viewState = srcString.Substring(i, j - i);

                //获得 EventValidation                
                string eventValidationFlag = "id=\"__EVENTVALIDATION\" value=\"";
                i = srcString.IndexOf(eventValidationFlag) + eventValidationFlag.Length;
                j = srcString.IndexOf("\"", i);
                string eventValidation = srcString.Substring(i, j - i);

                // Convert the text into the url encoding string
                viewState = System.Web.HttpUtility.UrlEncode(viewState);
                eventValidation = System.Web.HttpUtility.UrlEncode(eventValidation);

                //创建参数
                StringBuilder nvc = new StringBuilder();
                nvc.Append("__VIEWSTATE=" + viewState);
                nvc.Append("&__EVENTVALIDATION=" + eventValidation);
                nvc.Append("&DlistStatus=9");
                nvc.Append("&Dropdownlist1=9");
                nvc.Append("&useDateBegin_TS=" + from.Date.Tolong() + "000");
                //nvc.Append("&useDateBegin_TS=1388534400000");
                nvc.Append("&useDateBegin=" + from.ToString("yyyy-MM-dd"));
                nvc.Append(string.Format("&useDateBegin%24DDD%24C={0}:{0}", from.ToString("MM/dd/yyyy")));
                nvc.Append("&useDateEnd_TS=" + to.Date.Tolong() + "000");
                //nvc.Append("&useDateEnd_TS=1388707200000");
                nvc.Append("&useDateEnd=" + to.ToString("yyyy-MM-dd"));
                nvc.Append(string.Format("&useDateEnd%24DDD%24C={0}:{0}", to.ToString("MM/dd/yyyy")));
                nvc.Append("&LookDateBegin%24DDD%24C=" + to.ToString("MM/dd/yyyy"));
                nvc.Append("&LookDateEnd%24DDD%24C=" + to.ToString("MM/dd/yyyy"));
                nvc.Append("&btnQuery=%E6%9F%A5+%E8%AF%A2");
                nvc.Append("&ckbCDItems=on");

                orderHtml = HttpReader.HttpPostWith302(orderUrl, nvc.ToString(), "http://bjvrm.wumart.com/PurchaseOrder/SupPOsPrint.aspx", ref cookie);
            }
            catch (Exception ex)
            {
                Log.Error("GetOrder", ex);
                isError = true;
            }
            if (!string.IsNullOrEmpty(orderHtml))
            {
                IHtmlParser<List<OrderModel>> orderparser = new OrderParser();
                var orders = orderparser.ParseObject(orderHtml);
                IOrder orderimpl = new OrderImpl();
                foreach (var o in orders)
                {
                    orderimpl.Add(o);
                }
            }
            return result;
        }

        public List<NewsModel> GetNews(out bool isError)
        {
            List<NewsModel> result = new List<NewsModel>();
            //获得所有新闻
            isError = false;
            string newsUrl = "http://bjvrm.wumart.com/VRMManage/VRMMain.aspx";
            string nweHtml = null;
            try
            {
                nweHtml = HttpReader.HttpGet(newsUrl, ref cookie);
                //分析Get到的数据是否有302跳转到Timeout.aspx或者Error.aspx
                IHtmlParser<HtmlModel> getParser = new Page302ToErrorOrTimePageParser();
                var getResult = getParser.ParseObject(nweHtml);
                //Get出现错误，则返回
                if (getResult.IsError)
                {
                    isError = getResult.IsError;
                    Log.Error("GetNews", "Url:" + newsUrl + "&Error" + getResult.Html);
                    return result;
                }
            }
            catch (Exception ex)
            {
                Log.Error("GetNews", ex);
                isError = true;
            }
            finally
            {
                if (!isError)
                {
                    IHtmlParser<List<NewsModel>> newsParser = new NewsParser();
                    var titles = newsParser.ParseObject(nweHtml);
                    //获得数据库中不存在的新闻
                    INews implNew = new NewsImpl();
                    //获得新闻明细
                    try
                    {
                        result.ForEach(n =>
                        {
                            var nv = HttpUtility.ParseQueryString(n.DetailLink);
                            var id = nv.GetValues(0).First();
                            n.Detail = this.GetNewsDetail(id);

                            implNew.Add(n);
                        });
                    }
                    catch (Exception ex)
                    {
                        Log.Error("GetNews", ex);
                        isError = true;
                    }
                }
            }
            return result;
        }

        public Stream GetLoginCode()
        {
            string codeUrl = "http://bjvrm.wumart.com/VRMManage/CheckCode.aspx?id=0";
            try
            {
                return HttpReader.HttpGetStream(codeUrl, ref cookie);
            }
            catch (Exception ex)
            {
                Log.Error("GetLoginCode", ex);
            }
            return null;
        }

        public string GetNewsDetail(string identity)
        {
            string newDetailUrl = "http://bjvrm.wumart.com/InfoPublish/Detail.aspx?ID={0}";
            newDetailUrl = string.Format(newDetailUrl, identity);
            return HttpReader.HttpGetFakeAsChrome(newDetailUrl, "http://bjvrm.wumart.com/VRMManage/VRMMain.aspx", ref cookie);
        }


        public decimal GetMonthStatement(DateTime month, string supplierCode, out bool isError)
        {
            decimal result = decimal.Zero;
            isError = false;
            var now = DateTime.Now;
            TimeSpan ts = now - LastQueryStatementTime;
            var interval = double.Parse(System.Configuration.ConfigurationManager.AppSettings["DownloadStatementIntervalMinute"]);
            if (ts.TotalMinutes <= interval)
                return result;
            LastQueryStatementTime = now;

            //请求销量库存页面
            string statementUrl = "http://bjvrm.wumart.com/SalesVStock/StockVSales.aspx";
            string statementHtml = null;
            try
            {
                string srcString = HttpReader.HttpGet(statementUrl, ref cookie);

                //分析Get到的数据是否有302跳转到Timeout.aspx或者Error.aspx
                IHtmlParser<HtmlModel> getParser = new Page302ToErrorOrTimePageParser();
                var getResult = getParser.ParseObject(srcString);
                //Get出现错误，则返回
                if (getResult.IsError)
                {
                    isError = getResult.IsError;
                    Log.Error("GetStatement", "Url:" + statementUrl + "&Error" + getResult.Html);
                    return result;
                }

                //获得 ViewState                
                string viewStateFlag = "id=\"__VIEWSTATE\" value=\"";
                int i = srcString.IndexOf(viewStateFlag) + viewStateFlag.Length;
                int j = srcString.IndexOf("\"", i);
                string viewState = srcString.Substring(i, j - i);

                //获得 EventValidation                
                string eventValidationFlag = "id=\"__EVENTVALIDATION\" value=\"";
                i = srcString.IndexOf(eventValidationFlag) + eventValidationFlag.Length;
                j = srcString.IndexOf("\"", i);
                string eventValidation = srcString.Substring(i, j - i);

                // Convert the text into the url encoding string
                viewState = System.Web.HttpUtility.UrlEncode(viewState);
                eventValidation = System.Web.HttpUtility.UrlEncode(eventValidation);

                //创建查询
                StringBuilder nvcquery = new StringBuilder();
                nvcquery.Append("__EVENTTARGET=");
                nvcquery.Append("&__EVENTARGUMENT=");
                nvcquery.Append("&__VIEWSTATE=" + viewState);
                nvcquery.Append("&__EVENTVALIDATION=" + eventValidation);
                nvcquery.Append("&SUP_NO=" + supplierCode);
                nvcquery.Append("&DlistStore=0");
                nvcquery.Append("&SelYearMonth=" + month.ToString("yyyy-MM"));
                nvcquery.Append("&Merch_Code=");
                nvcquery.Append("&Merch_Name=");
                nvcquery.Append("&CheckBox3=on");
                nvcquery.Append("&Button1=查询");
                statementHtml = HttpReader.HttpPost(statementUrl, nvcquery.ToString(), statementUrl, ref cookie);

                //创建导出excel
                StringBuilder nvc = new StringBuilder();
                nvc.Append("__EVENTTARGET=btnSave");
                nvc.Append("&__EVENTARGUMENT=");
                nvc.Append("&__VIEWSTATE=" + viewState);
                nvc.Append("&__EVENTVALIDATION=" + eventValidation);
                nvc.Append("&SUP_NO=" + supplierCode);
                nvc.Append("&DlistStore=0");
                nvc.Append("&SelYearMonth=" + month.ToString("yyyy-MM"));
                nvc.Append("&Merch_Code=");
                nvc.Append("&Merch_Name=");
                nvc.Append("&CheckBox3=on");
                statementHtml = HttpReader.HttpPost(statementUrl, nvc.ToString(), statementUrl, ref cookie);
            }
            catch (Exception ex)
            {
                Log.Error("GetMonthStatement", ex);
                isError = true;
            }
            if (!string.IsNullOrEmpty(statementHtml))
            {
                IHtmlParser<List<StatementModel>> orderparser = new SaleVolumnOfDayParser();
                var orders = orderparser.ParseObject(statementHtml);
                if (orders.Count > 0)
                {
                    result = orders.Sum(p => p.SaleVolumn);
                }
            }
            return result;
        }


        public void UpdateGoodsReceiveInfo(DateTime from, DateTime to, out bool isError)
        {
            isError = false;
            List<OrderModel> result = new List<OrderModel>();
            //请求订单页面
            string orderUrl = "http://bjvrm.wumart.com/GoodsReceive/OrderQuery.aspx";
            string orderHtml = null;
            try
            {
                string srcString = HttpReader.HttpGet(orderUrl, ref cookie);

                //分析Get到的数据是否有302跳转到Timeout.aspx或者Error.aspx
                IHtmlParser<HtmlModel> getParser = new Page302ToErrorOrTimePageParser();
                var getResult = getParser.ParseObject(srcString);
                //Get出现错误，则返回
                if (getResult.IsError)
                {
                    isError = getResult.IsError;
                    Log.Error("GetGoodsReceiveInfo", "Url:" + orderUrl + "&Error" + getResult.Html);
                    return;
                }

                //获得 ViewState                
                string viewStateFlag = "id=\"__VIEWSTATE\" value=\"";
                int i = srcString.IndexOf(viewStateFlag) + viewStateFlag.Length;
                int j = srcString.IndexOf("\"", i);
                string viewState = srcString.Substring(i, j - i);

                //获得 EventValidation                
                string eventValidationFlag = "id=\"__EVENTVALIDATION\" value=\"";
                i = srcString.IndexOf(eventValidationFlag) + eventValidationFlag.Length;
                j = srcString.IndexOf("\"", i);
                string eventValidation = srcString.Substring(i, j - i);

                // Convert the text into the url encoding string
                viewState = System.Web.HttpUtility.UrlEncode(viewState);
                eventValidation = System.Web.HttpUtility.UrlEncode(eventValidation);

                //创建参数
                StringBuilder nvc = new StringBuilder();
                nvc.Append("__VIEWSTATE=" + viewState);
                nvc.Append("&__EVENTVALIDATION=" + eventValidation);
                nvc.Append("&DlistStore=0");
                nvc.Append("&DListType=0");
                nvc.Append("&useDateBegin_TS=" + from.Date.Tolong() + "000");
                nvc.Append("&useDateBegin=" + from.ToString("yyyy-MM-dd"));
                nvc.Append("&useDateBegin_DDDWS=0:0:12000:443.3699951171875:79:0:0:0");
                nvc.Append("&useDateBegin_DDD_C_FNPWS=0:0:-1:0:0:0:0:0:");
                //useDateBegin$DDD$C 01/02/2014:01/01/2014
                var t = from.AddDays(1);
                nvc.Append("&useDateBegin$DDD$C=" + t.ToString("MM/dd/yyyy") + ":" + from.ToString("MM/dd/yyyy"));
                nvc.Append("&useDateBegin$DDD$C$CVS=");
                nvc.Append("&useDateBegin$CVS=");
                nvc.Append("&useDateEnd_TS=");
                nvc.Append("&useDateEnd=" + to.ToString("yyyy-MM-dd"));
                nvc.Append("&useDateEnd_DDDWS=0:0:-1:0:0:0:0:0:");
                nvc.Append("&useDateEnd_DDD_C_FNPWS=0:0:-1:0:0:0:0:0:");
                nvc.Append("&useDateEnd$DDD$C=" + to.ToString("MM/dd/yyyy"));
                nvc.Append("&useDateEnd$DDD$C$CVS=");
                nvc.Append("&useDateEnd$CVS=");
                nvc.Append("&DListStatus=0");
                nvc.Append("&txtbPONO=0");
                nvc.Append("&btnQuery=%E6%9F%A5+%E8%AF%A2");
                orderHtml = HttpReader.HttpPost(orderUrl, nvc.ToString(), orderUrl, ref cookie);
            }
            catch (Exception ex)
            {
                Log.Error("GetOrder", ex);
                isError = true;
            }
            if (!string.IsNullOrEmpty(orderHtml))
            {
                IHtmlParser<List<OrderModel>> orderparser = new ReceiveGoodsParser();
                var orders = orderparser.ParseObject(orderHtml);
                //IOrder orderimpl = new OrderImpl();
                //orderimpl.UpdateReceiveGoods(this.CompanyID, orders);
            }
        }


        private string GetDeliverySheetWithSotre(DateTime from, DateTime to, out bool isError)
        {
            isError = false;
            //请求订单(直流按店)页面
            string orderUrl = "http://bjvrm.wumart.com/PurchaseOrder/SupPOsPrintHD.aspx";
            string orderHtml = null;
            try
            {
                string srcString = HttpReader.HttpGet(orderUrl, ref cookie);

                //分析Get到的数据是否有302跳转到Timeout.aspx或者Error.aspx
                IHtmlParser<HtmlModel> getParser = new Page302ToErrorOrTimePageParser();
                var getResult = getParser.ParseObject(srcString);
                //Get出现错误，则返回
                if (getResult.IsError)
                {
                    isError = getResult.IsError;
                    Log.Error("GetOrderWithStore", "Url:" + orderUrl + "&Error" + getResult.Html);
                    return orderHtml;
                }

                //获得 ViewState                
                string viewStateFlag = "id=\"__VIEWSTATE\" value=\"";
                int i = srcString.IndexOf(viewStateFlag) + viewStateFlag.Length;
                int j = srcString.IndexOf("\"", i);
                string viewState = srcString.Substring(i, j - i);

                //获得 EventValidation                
                string eventValidationFlag = "id=\"__EVENTVALIDATION\" value=\"";
                i = srcString.IndexOf(eventValidationFlag) + eventValidationFlag.Length;
                j = srcString.IndexOf("\"", i);
                string eventValidation = srcString.Substring(i, j - i);

                // Convert the text into the url encoding string
                viewState = System.Web.HttpUtility.UrlEncode(viewState);
                eventValidation = System.Web.HttpUtility.UrlEncode(eventValidation);

                //创建参数
                StringBuilder nvc = new StringBuilder();
                nvc.Append("__VIEWSTATE=" + viewState);
                nvc.Append("&__EVENTVALIDATION=" + eventValidation);
                nvc.Append("&DlistStatus=9");
                nvc.Append("&Dropdownlist1=9");
                nvc.Append("&useDateBegin_TS=" + from.Date.Tolong() + "000");
                //nvc.Append("&useDateBegin_TS=1388534400000");
                nvc.Append("&useDateBegin=" + from.ToString("yyyy-MM-dd"));
                nvc.Append(string.Format("&useDateBegin%24DDD%24C={0}:{0}", from.ToString("MM/dd/yyyy")));
                nvc.Append("&useDateEnd_TS=" + to.Date.Tolong() + "000");
                //nvc.Append("&useDateEnd_TS=1388707200000");
                nvc.Append("&useDateEnd=" + to.ToString("yyyy-MM-dd"));
                nvc.Append(string.Format("&useDateEnd%24DDD%24C={0}:{0}", to.ToString("MM/dd/yyyy")));
                nvc.Append("&LookDateBegin%24DDD%24C=" + to.ToString("MM/dd/yyyy"));
                nvc.Append("&LookDateEnd%24DDD%24C=" + to.ToString("MM/dd/yyyy"));
                nvc.Append("&btnQuery=%E6%9F%A5+%E8%AF%A2");

                orderHtml = HttpReader.HttpPostWith302(orderUrl, nvc.ToString(), orderUrl, ref cookie);

                //获取明细
            }
            catch (Exception ex)
            {
                Log.Error("GetOrderWithStore", ex);
                isError = true;
            }
            return orderHtml;
        }

        public List<OrderDetailModel> GetOrderDetail(string orderNo, DateTime from, DateTime to, out bool isError)
        {
            isError = false;
            List<OrderDetailModel> result = new List<OrderDetailModel>();
            //请求订单(直流按店)页面
            string orderUrl = "http://bjvrm.wumart.com/PurchaseOrder/SupPOsPrintHD.aspx";
            string orderHtml = null;
            string srcString = this.GetDeliverySheetWithSotre(from, to, out isError);
            //获得订单号与控件关联信息
            IHtmlParser<List<OrderModel>> orderWithStores = new OrderWithStoreParser();
            List<OrderModel> ows = orderWithStores.ParseObject(srcString);
            string ctrid = ows.Single(w => w.Code == orderNo).CtrID;
            try
            {
                //分析Get到的数据是否有302跳转到Timeout.aspx或者Error.aspx
                IHtmlParser<HtmlModel> getParser = new Page302ToErrorOrTimePageParser();
                var getResult = getParser.ParseObject(srcString);
                //Get出现错误，则返回
                if (getResult.IsError)
                {
                    isError = getResult.IsError;
                    Log.Error("GetOrderDetail", "Url:" + orderUrl + "&Error" + getResult.Html);
                    return result;
                }

                //获得 ViewState                
                string viewStateFlag = "id=\"__VIEWSTATE\" value=\"";
                int i = srcString.IndexOf(viewStateFlag) + viewStateFlag.Length;
                int j = srcString.IndexOf("\"", i);
                string viewState = srcString.Substring(i, j - i);

                //获得 EventValidation                
                string eventValidationFlag = "id=\"__EVENTVALIDATION\" value=\"";
                i = srcString.IndexOf(eventValidationFlag) + eventValidationFlag.Length;
                j = srcString.IndexOf("\"", i);
                string eventValidation = srcString.Substring(i, j - i);

                // Convert the text into the url encoding string
                viewState = System.Web.HttpUtility.UrlEncode(viewState);
                eventValidation = System.Web.HttpUtility.UrlEncode(eventValidation);

                //创建参数
                StringBuilder nvc = new StringBuilder();
                nvc.Append("__EVENTTARGET=");
                nvc.Append("&__EVENTARGUMENT=");
                nvc.Append("&__VIEWSTATE=" + viewState);
                nvc.Append("&__EVENTVALIDATION=" + eventValidation);
                nvc.Append("&btnTXT=%E5%AF%BC%E5%87%BATXT");
                nvc.Append("&" + ctrid.Replace("$", "%24") + "=on");//MyDataGrid%24ctl04%24ChkSelect=on
                orderHtml = HttpReader.HttpPostWith302(orderUrl, nvc.ToString(), orderUrl, ref cookie);
            }
            catch (Exception ex)
            {
                Log.Error("GetOrderWithStore", ex);
                isError = true;
            }
            if (!string.IsNullOrEmpty(orderHtml))
            {
                IHtmlParser<List<OrderDetailModel>> orderparser = new OrderDetailParser();
                result = orderparser.ParseObject(orderHtml);
                //保存到数据库中
                IOrderDetail orderimpl = new OrderDetailImpl();
                foreach (var d in result)
                {
                    orderimpl.Add(d);
                }
            }
            return result;
        }


        public Guid CompanyID
        {
            set;
            get;
        }
    }
}
